package me.haoliang.akkaDemo

import akka.actor.{Actor, ActorRef, Props}

import scala.io.Source._

/**
  * author: planck 
  * createTime: 2016/11/3.
  */
case class StartProcessFileMsg()

class WordCounterActor(fileName: String) extends Actor {

  private var running = false

  private var totalLines = 0

  private var linesProcessed = 0

  private var result = 0

  private var fileSender: Option[ActorRef] = None


  override def receive: Receive = {
    case StartProcessFileMsg() => {
      if (running) {
        println("running")
      } else {
        running = true
        fileSender = Some(sender)
        println("sleep start")
        Thread.sleep(5000)
        println("sleep over")
        fromFile(fileName).getLines().foreach(line => {
          context.actorOf(Props[StringCounterActor]) ! ProcessStringMsg(line)
          totalLines += 1
        })
      }
    }
    case StringProcessedMsg(words) => {
      result += words
      linesProcessed += 1
      if (linesProcessed == totalLines) {
        fileSender.get ! result
      }
    }
  }
}
